import axios from 'axios';
import { getQueryVariable } from './common.js';
axios.defaults.baseURL = process.env.VUE_APP_PRODURL.replace(/\/([a-z]|_)+\.do$/, ''); // 去掉XXX.do的部分
axios.defaults.timeout = 120 * 1000;

/**
 * 封装请求
 * 开发环境默认 vertica, 生产环境默认 impala
 * @param option 包含以下配置
 *  【可选】type：数据源类型，可选值为"impala"、"hive"、"vertica" 等
 *  【必选】sql：要查询的sql 默认以vertica为主
 *  【可选】sqlTip：sql提示文本标记
 *  【可选】log：控制台输出时的标识
 *  【可选】log_mode：输出临时文件
 *  【可选】cas: 返回数据字段的大小写，可选值为
 *         'upper': 转成大写
 *         'lower': 转成小写
 *         'ignore'：不转换
 *         默认为'ignore'
 *  【可选】config: axios 的配置项
 *
 */

let defaultOption = {
    type: process.env.VUE_APP_DB,
    sql: '',
    sqlTip: '',
    log: null,
    log_mode: null,
    cas: 'upper',
    config: null,
    no_session: true, // 开发环境不使用session
};
let smsql = getQueryVariable('smsql');


// ajax请求
const ajax = option => {
    switch (option.requestType) {
        case 'update':
            return ajaxForUpdate(option);
        default:
            return ajaxForDefault(option);
    }
};

// 更新专用的ajax请求
const ajaxForUpdate = option => {
    let opt = Object.assign({}, defaultOption, option);
    let config = opt.config ? opt.config : {};

    let sqlConfig = {};
    if (opt.sqlBatch && opt.sqlBatch instanceof Array && opt.sqlBatch.length > 0) {
        let count = opt.sqlBatch.length;
        sqlConfig["batch_count"] = count;

        for (let i = 0; i < count; i++) {
            let sql = opt.sqlBatch[i];
            // 如果需要打印sql到控制台
            if (smsql && opt.sqlTip) {
                console.log('');
                console.log(`=============================start  ${opt.sqlTip}  (${i})=============================`);
                console.log(sql);
                console.log(`===============================end  ${opt.sqlTip}  (${i})=============================`);
            }

            sqlConfig["batch_sql_" + i] = encodeURIComponent(sql);
        }
    } else {
        // 根据环境及是否配置有impala的参数，使用不同sql参数
        let sql = opt.sql
        // 如果需要打印sql到控制台
        if (smsql && opt.sqlTip) {
            console.log('');
            console.log(`=============================start  ${opt.sqlTip}=============================`);
            console.log(sql);
            console.log(`===============================end  ${opt.sqlTip}=============================`);
        }

        sqlConfig["sql"] = encodeURIComponent(sql);
    }

    // 配置默认url
    if (!config.url) {
        // config.url = process.env.NODE_ENV == 'development' ? 'just_update.do' : 'update.do';
        config.url = "just_update.do";
    }

    config.headers = {
        "Cache-Control": "no-cache",
    };

    // 配置默认为post查询
    if (!config.method || config.method === 'post') {
        config.method = 'post';
        config.data = Object.assign({}, config.data, sqlConfig, {
            requestType: "update",
            type: opt.type,
            cas: opt.cas,
            sqlTip: opt.sqlTip,
            log: opt.log,
            log_mode: opt.log_mode,
            // auth: getAuthId(),
            no_session: opt.no_session,
        });
    } else if (config.method === 'get') {
        config.params = Object.assign({}, sqlConfig, {
            type: opt.type,
            cas: opt.cas,
            sqlTip: opt.sqlTip,
            log: opt.log,
            log_mode: opt.log_mode,
            // auth: getAuthId(),
            no_session: opt.no_session,
        });
    }

    config.errorCodes = [-1, -2];

    return new Promise((resolve, reject) => {
        axios(config)
            .then(res => {
                let bundle = res.data;  
                let result = bundle.data || [];
                if (result.length == 1 && typeof result[0] == 'object' && Object.keys(result[0]).length == 0) {
                    result = [];
                }
                if (bundle.code == 0) {
                    resolve(result);
                } else {
                    const fmsg = bundle.message;
                    const smsg = fmsg.substring(0, fmsg.indexOf("\tat"));

                    const e = new Error(smsg);
                    e.fullMessage = fmsg;
                    
                    throw e;
                }
            }).catch(e => {
                if (process.env.NODE_ENV == 'development') {
                    console.error(e);
                }
                reject(e);
            });
    })
};

const ajaxForDefault = option => {
    let opt = Object.assign({}, defaultOption, option);
    let config = opt.config ? opt.config : {};
    let sqlConfig = {};

    if (!config.url) {
        // config.url = process.env.NODE_ENV == 'development' ? 'just_search.do' : 'search.do';
        config.url = 'just_search.do';
    }

    // 根据环境及是否配置有impala的参数，使用不同sql参数
    let sql = opt.sql
    // 如果需要打印sql到控制台
    if (smsql && opt.sqlTip) {
        console.log('');
        console.log(`=============================start  ${opt.sqlTip}=============================`);
        console.log(sql);
        console.log(`===============================end  ${opt.sqlTip}=============================`);
    }
    sqlConfig["sql"] = encodeURIComponent(sql);

    // 配置默认为post查询
    config.method = 'post';
    config.data = Object.assign({}, config.data, sqlConfig, {
        type: opt.type,
        cas: opt.cas,
        sqlTip: opt.sqlTip,
        log: opt.log,
        log_mode: opt.log_mode,
        no_session: opt.no_session,
    });

    return new Promise((resolve, reject) => {
        axios(config)
            .then(res => {
                let bundle = res.data;  
                let result = bundle.data || [];
                if (result.length == 1 && typeof result[0] == 'object' && Object.keys(result[0]).length == 0) {
                    result = [];
                }
                if (bundle.code == 0) {
                    resolve(result);
                } else {
                    const fmsg = bundle.message;
                    const smsg = fmsg.substring(0, fmsg.indexOf("\tat"));

                    const e = new Error(smsg);
                    e.fullMessage = fmsg;
                    
                    throw e;
                }
            }).catch(e => {
                if (process.env.NODE_ENV == 'development') {
                    console.error(e);
                }
                reject(e);
            });
    })
};

export default ajax;